<template>
  <view class="watch-ad-page">
    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 用户积分信息 -->
      <view class="points-info">
        <view class="points-card">
          <view class="points-label">当前积分</view>
          <view class="points-value">{{ userPoints }}</view>
        </view>
        <view class="today-earned">
          <text>今日已获得: {{ todayEarned }} 积分</text>
        </view>
      </view>
      
      <!-- 广告奖励组件 -->
      <!-- #ifdef MP-WEIXIN -->
      <AdReward @reward-earned="handleRewardEarned" />
      <!-- #endif -->
      
      <!-- #ifdef H5 -->
      <H5AdReward @reward-earned="handleRewardEarned" @error="handleAdError" />
      <!-- #endif -->
      
      <!-- 积分获取记录 -->
      <view class="points-history">
        <view class="history-title">
          <text>最近获得记录</text>
          <text class="view-all" @click="viewAllHistory">查看全部</text>
        </view>
        
        <view class="history-list">
          <view 
            v-for="(record, index) in recentRecords" 
            :key="index"
            class="history-item"
          >
            <view class="record-info">
              <view class="record-source">{{ record.sourceName }}</view>
              <view class="record-time">{{ formatTime(record.createdAt) }}</view>
            </view>
            <view class="record-points">+{{ record.amount }}</view>
          </view>
          
          <view v-if="recentRecords.length === 0" class="empty-records">
            <image src="/static/icons/empty.png" mode="aspectFit"></image>
            <text>暂无获得记录</text>
          </view>
        </view>
      </view>
      
      <!-- 广告规则说明 -->
      <view class="ad-rules">
        <view class="rules-title">积分获取规则</view>
        <view class="rules-list">
          <view class="rule-item">
            <view class="rule-type">观看15-30秒视频广告</view>
            <view class="rule-reward">+0.5积分</view>
          </view>
          <view class="rule-item">
            <view class="rule-type">观看30-60秒视频广告</view>
            <view class="rule-reward">+1积分</view>
          </view>
          <view class="rule-item">
            <view class="rule-type">完成互动广告</view>
            <view class="rule-reward">+1.5积分</view>
          </view>
        </view>
        
        <view class="rules-note">
          <text>• 每日最多可观看50次广告</text>
          <text>• 需要完整观看才能获得积分</text>
          <text>• 积分立即到账，可用于兑换打印服务</text>
        </view>
      </view>
    </view>
    
    <!-- Banner广告位 -->
    <view class="banner-ad-container" v-if="showBannerAd">
      <!-- Banner广告会通过原生组件显示 -->
    </view>
  </view>
</template>

<script>
import AdReward from '@/components/AdReward.vue'
// #ifdef H5
import H5AdReward from '@/components/H5AdReward.vue'
// #endif
import adManager from '@/utils/adManager.js'
import { getPointsBalance, getPointsStats } from '@/api/points.js'

export default {
  name: 'WatchAdPage',
  components: {
    AdReward,
    // #ifdef H5
    H5AdReward
    // #endif
  },
  
  data() {
    return {
      userPoints: 0,
      todayEarned: 0,
      recentRecords: [],
      showBannerAd: false,
      statusBarHeight: 0
    }
  },
  
  onLoad() {
    this.initStatusBar()
    this.loadUserData()
    this.loadRecentRecords()
    this.initBannerAd()
  },
  
  onShow() {
    // 页面显示时刷新数据
    this.loadUserData()
  },
  
  onHide() {
    // 页面隐藏时隐藏Banner广告
    adManager.hideBannerAd()
  },
  
  onUnload() {
    // 页面卸载时销毁Banner广告
    adManager.destroyBannerAd()
  },
  
  // 监听积分更新事件
  onReady() {
    uni.$on('points-updated', this.handlePointsUpdated)
  },
  
  beforeDestroy() {
    uni.$off('points-updated', this.handlePointsUpdated)
  },
  
  methods: {
    /**
     * 初始化状态栏高度
     */
    initStatusBar() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
      
      // 设置CSS变量
      // #ifdef H5
      if (document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
      }
      // #endif
      
      // #ifndef H5
      // 小程序和APP环境下，直接使用rpx单位
      const statusBarHeightRpx = this.statusBarHeight * 2 // px转rpx
      if (typeof document !== 'undefined' && document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', statusBarHeightRpx + 'rpx')
      }
      // #endif
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },
    
    /**
     * 加载用户数据
     */
    async loadUserData() {
      try {
        // 获取积分余额
        const balanceResult = await getPointsBalance()
        if (balanceResult && balanceResult.success) {
          this.userPoints = balanceResult.data.availablePoints || 0
        }
        
        // 获取积分统计
        const statsResult = await getPointsStats()
        if (statsResult && statsResult.success) {
          this.todayEarned = statsResult.data.todayEarned || 0
        }
      } catch (error) {
        console.error('加载用户积分失败:', error)
        // 使用默认值
        this.userPoints = 0
        this.todayEarned = 0
      }
    },
    
    /**
     * 加载最近记录
     */
    async loadRecentRecords() {
      try {
        // 由于getPointsHistory函数不存在，我们使用模拟数据
        // 在实际项目中，这里应该调用正确的API
        this.recentRecords = [
          {
            id: 1,
            source: 'ad_watch',
            amount: 1,
            createdAt: Date.now() - 300000, // 5分钟前
            sourceName: '观看广告'
          },
          {
            id: 2,
            source: 'ad_watch',
            amount: 0.5,
            createdAt: Date.now() - 1800000, // 30分钟前
            sourceName: '观看广告'
          },
          {
            id: 3,
            source: 'ad_watch',
            amount: 1.5,
            createdAt: Date.now() - 3600000, // 1小时前
            sourceName: '观看广告'
          }
        ]
      } catch (error) {
        console.error('加载积分记录失败:', error)
        this.recentRecords = []
      }
    },
    
    /**
     * 获取积分来源名称
     */
    getSourceName(source) {
      const sourceMap = {
        'ad_watch': '观看广告',
        'invite_register': '邀请注册',
        'invite_consume': '邀请消费',
        'recharge_bonus': '充值奖励',
        'activity': '活动奖励',
        'admin_adjust': '系统调整'
      }
      return sourceMap[source] || '其他'
    },
    
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    },
    
    /**
     * 处理奖励获得
     */
    handleRewardEarned(reward) {
      this.userPoints += reward.points
      this.todayEarned += reward.points
      
      // 刷新最近记录
      this.loadRecentRecords()
    },
    
    /**
     * 处理积分更新事件
     */
    handlePointsUpdated() {
      this.loadUserData()
      this.loadRecentRecords()
    },
    
    /**
     * 查看全部历史记录
     */
    viewAllHistory() {
      uni.navigateTo({
        url: '/pages/points/history'
      })
    },
    
    /**
     * 处理广告错误
     */
    handleAdError(error) {
      console.error('广告错误:', error)
      uni.showToast({
        title: error.message || '广告加载失败',
        icon: 'none'
      })
    },
    
    /**
     * 初始化Banner广告
     */
    initBannerAd() {
      // 延迟显示Banner广告，避免影响用户体验
      setTimeout(() => {
        // #ifdef MP-WEIXIN
        adManager.createBannerAd({
          style: {
            top: uni.getSystemInfoSync().windowHeight - 100
          }
        })
        // #endif
        
        // #ifdef H5
        adManager.createBannerAd({
          containerId: 'h5-banner-ad-container',
          width: 320,
          height: 50
        })
        // #endif
        
        // 延迟显示
        setTimeout(() => {
          adManager.showBannerAd()
          this.showBannerAd = true
        }, 2000)
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.watch-ad-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #667eea 0%, #f8f9fa 30%);
}

// 导航栏样式
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: #667eea;
  position: relative;
  z-index: 100;
  box-sizing: border-box;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.7;
    transform: scale(0.95);
  }
}

.back-icon {
  font-size: 36rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.nav-right {
  width: 80rpx;
  height: 60rpx;
}

.page-content {
  padding: 20rpx;
  padding-bottom: 120rpx; // 为Banner广告留出空间
}

.points-info {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.points-card {
  text-align: center;
  margin-bottom: 20rpx;
}

.points-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.points-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #667eea;
}

.today-earned {
  text-align: center;
  font-size: 24rpx;
  color: #999;
}

.points-history {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.history-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.view-all {
  font-size: 24rpx;
  color: #667eea;
  font-weight: normal;
}

.history-list {
  .history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .record-info {
    flex: 1;
  }
  
  .record-source {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 4rpx;
  }
  
  .record-time {
    font-size: 24rpx;
    color: #999;
  }
  
  .record-points {
    font-size: 28rpx;
    font-weight: bold;
    color: #52c41a;
  }
  
  .empty-records {
    text-align: center;
    padding: 60rpx 0;
    color: #999;
    
    image {
      width: 120rpx;
      height: 120rpx;
      margin-bottom: 20rpx;
      opacity: 0.5;
    }
    
    text {
      font-size: 28rpx;
    }
  }
}

.ad-rules {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
}

.rules-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.rules-list {
  margin-bottom: 20rpx;
}

.rule-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.rule-type {
  font-size: 26rpx;
  color: #666;
}

.rule-reward {
  font-size: 26rpx;
  font-weight: bold;
  color: #52c41a;
}

.rules-note {
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  text {
    display: block;
    font-size: 24rpx;
    color: #999;
    line-height: 1.6;
    margin-bottom: 8rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.banner-ad-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: rgba(0, 0, 0, 0.05);
  z-index: 999;
}
</style>